package com.nightsoul.shirotest;

import java.io.File;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;

public class Launcher {

	public static void main(String[] args) throws Exception {
		String userDir = System.getProperty("user.dir");
		File webapp = new File(userDir, "src/main/webapp");
		System.out.println(webapp);
		String contextPath = "/" + userDir.substring(userDir.lastIndexOf(File.separator) + 1);
		System.out.println(contextPath);

		Server server = new Server(8080);

		WebAppContext webAppContext = new WebAppContext(webapp.getAbsolutePath(), contextPath);
		// 必须添加AnnotationConfiguration配置方式才能扫描注解
		webAppContext.setConfigurations(new Configuration[]{new AnnotationConfiguration(), new JettyWebXmlConfiguration(),
			new WebXmlConfiguration(), new WebInfConfiguration(),
			new PlusConfiguration(), new MetaInfConfiguration(),
		    new FragmentConfiguration(), new EnvConfiguration()});
		// 必须设置该属性用于指定哪些位置的类需要扫描注解(@WebServlet等)
		webAppContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/bin/");
		String webXmlPath = new File(webapp, "WEB-INF\\web.xml").getAbsolutePath();
		// 使用绝对路径或相对路径设置web.xml路径，不设置默认为相对路径WEB-INF/web.xml，而当前目录为项目根目录，故文件找不到，进而shiro配置无效
		webAppContext.setDescriptor(webXmlPath);
		webAppContext.setDescriptor("src\\main\\webapp\\WEB-INF\\web.xml");

		HandlerCollection handlers = new HandlerCollection();
		handlers.addHandler(webAppContext);
		server.setHandler(handlers);

		server.start();
		server.join();
	}

}
